import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store/request";

Vue.use(VueRouter)

const routes = [
  {
    path:'',
    redirect:'/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '*',
    name: '404',
    component: () => import('../views/404.vue')
  }
]

const router = new VueRouter({
 // mode:'history',
  base:'process.env.BASE_URL',
  routes
})

//刷新页面 路由会重置
export const setRouters = () =>{
  const  storeMenus = localStorage.getItem("menus");
  if (storeMenus){
    //拼装路由
    const manageRoute={path: '/',name:'Manage' , component: () => import('../views/Manage.vue'), redirect:"/login", children:[
        {path:'person',name:'个人信息', component:()=>import('../views/Person.vue') },
        {path:'Modify',name:'修改密码', component:()=>import('../views/Modify.vue') },
      ]}
    const menus = JSON.parse(storeMenus)
    menus.forEach(item =>{
      if (item.path){
        let itemMenu ={ path: item.path.replace("/",""), name:item.name, component:()=>import('../views/'+item.pagePath+'.vue')}
        manageRoute.children.push(itemMenu)
      }else if(item.children.length) {
        item.children.forEach(item => {
          if (item.path) {
            let itemMenu = {
              path: item.path.replace("/", ""),
              name: item.name,
              component: () => import('../views/' + item.pagePath + '.vue')
            }
            manageRoute.children.push(itemMenu)
          }
        })
      }
    })
    const currentRouters =  router.getRoutes().map(v =>v.name)
    if (!currentRouters.includes('Manage')){
      //动态添加到现在的路由对象中
      router.addRoute(manageRoute)
    }
  }
}

setRouters()


//路由守卫
router.beforeEach((to,from,next)=>{
  window.document.title=to.name
  store.state.currentPathName = to.name
  next();
})

export default router
